﻿using System;
using System.Collections.Generic;
using System.Text;

namespace KGE.Define
{
    public class KeyStream
    {
        public class KeyInfo
        {
            public Microsoft.DirectX.DirectInput.Key Key;
            public KGE.Define.KeyState State;
            public double Time;
        }
        public double Interval = 1.0 / 6.0;
        Util.HDTimer timer = new Util.HDTimer();
        List<KeyInfo> buffer = new List<KeyInfo>();
        public void Add(KeyInfo ki)
        {
            //if (isCanAdd == false)
            //{
            //    if (ki.Key == banKey)
            //    {
            //        if (ki.State == KeyState.Up)
            //        {
            //            isCanAdd = true;
            //        }
            //        else
            //        {
            //            return;
            //        }
            //    }
            //    else
            //    {
            //        return;
            //    }
            //}
            //if (Last != null)
            //{
            //    if (ki.Key == Last.Key && ki.State == Last.State)
            //    {
            //        return;
            //    }
            //}
            timer.Reset();
            //if (buffer.Count > 0)
            //{
            //    if (Last.State == KeyState.Hold)
            //    {
            //        return;
            //    }
            //}

            ki.Time = timer.TotalSeconds;
            buffer.Add(ki);
        }
        public KeyInfo Last
        {
            get
            {
                if (buffer.Count > 0)
                {
                    return buffer[buffer.Count - 1];
                }
                return null;
            }
        }
        //bool isCanAdd = true;
        //Microsoft.DirectX.DirectInput.Key banKey;
        //public void Ban(Microsoft.DirectX.DirectInput.Key key)
        //{
        //    banKey = key;
        //    isCanAdd = false;
        //}
        public void Update()
        {
            timer.Record();
            if (timer.Seconds > Interval)
            {
                buffer.Clear();
            }
        }
        new public string ToString()
        {
            string str = "";
            for (int i = buffer.Count - 1; i > 1; i--)
            {
                if (buffer[i].Time - buffer[i - 1].Time > Interval)
                {
                    buffer.RemoveRange(0, i);
                    break;
                }
            }
            for (int i = 0; i < buffer.Count; i++)
            {
                str += buffer[i].State.ToString() + "-";
                str += buffer[i].Key.ToString();
                if (i + 1 < buffer.Count)
                {
                    str += ",";
                }
            }
            return str.ToLower();
        }
    }

}
